package com.freedom.admin.application.service.query;

import com.freedom.admin.application.converter.DeptConverter;
import com.freedom.admin.domain.repository.SysDeptRepository;
import com.freedom.admin.infrastructure.persistence.pojo.bo.DeptBO;
import com.freedom.admin.infrastructure.persistence.pojo.query.DeptQuery;
import com.freedom.admin.infrastructure.persistence.pojo.vo.dept.DeptTreeVO;
import com.freedom.admin.infrastructure.persistence.pojo.vo.dept.DeptVO;
import com.freedom.common.framework.pojo.OptionVO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
@RequiredArgsConstructor
public class DeptQueryService {

    private final SysDeptRepository deptRepository;

    private final DeptConverter deptConverter;

    public List<DeptTreeVO> listDeptTree(DeptQuery queryParam) {
        List<DeptBO> deptBOList = deptRepository.listDept(queryParam);
        return recursionTree(0, deptBOList);
    }

    public List<OptionVO> listDeptOption() {
        List<DeptBO> deptBOList = deptRepository.listDept(null);
        return recursionOptionTree(0, deptBOList);
    }

    public DeptVO findDeptDetail(Integer deptId) {
        DeptBO deptBO = deptRepository.findById(deptId);
        return deptConverter.toVO(deptBO);
    }


    private List<DeptTreeVO> recursionTree(Integer parentId, List<DeptBO> deptBOList) {
        List<DeptTreeVO> deptTreeVOList = new ArrayList<>();
        deptBOList.stream().filter(item -> item.getId().equals(parentId))
                .forEach(item -> {
                    DeptTreeVO deptTreeVO = deptConverter.toTreeVO(item);
                    deptTreeVO.setChildren(recursionTree(item.getId(), deptBOList));
                    deptTreeVOList.add(deptTreeVO);
                });
        return deptTreeVOList;
    }

    private List<OptionVO> recursionOptionTree(Integer parentId, List<DeptBO> deptBOList) {
        List<OptionVO> optionVOList = new ArrayList<>();
        deptBOList.stream().filter(item -> item.getId().equals(parentId))
                .forEach(item -> {
                    OptionVO optionVO = new OptionVO(item.getId(), item.getName());
                    optionVO.setChildren(recursionOptionTree(item.getId(), deptBOList));
                    optionVOList.add(optionVO);
                });
        return optionVOList;
    }
}
